# -*- coding: utf-8 -*-
# Author:jiang
# 2021/9/3 15:50
import shelve,time

from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
import yaml
from selenium.webdriver.common.by import By

class BasePage:
    _driver = None
    _base_url = ""
    def __init__(self, driver: WebDriver = None):
        if driver is None:
            self.option = webdriver.ChromeOptions()
            self.option.add_experimental_option("w3c", False)
            self._driver = webdriver.Chrome(chrome_options=self.option)
            self._driver.maximize_window()
            self._driver.implicitly_wait(5)
        else:
            self._driver = driver

        if self._base_url != "":
            self.login_session()
            if self.checkSession()==0:
                self.add_cookies()
    def quit(self):
        self._driver.quit()
    def find(self, by, locator):
        return self._driver.find_element(by, locator)
    def finds(self, by, locator):
        return self._driver.find_elements(by, locator)
    def wait_for_click(self, locator, time=10):
        WebDriverWait(self._driver, time).until(expected_conditions.element_to_be_clickable(locator))

    def wait_for_element(self, conditions, time=10):
        WebDriverWait(self._driver, time).until(conditions)
    def add_cookies(self):
        self._driver.get(self._base_url)
        username, password = yaml.safe_load(open("../yaml/username.yaml", encoding="utf-8"))[0]
        self._driver.find_element(By.ID, 'username').send_keys(username)
        self._driver.find_element(By.ID, 'password').send_keys(password)
        time.sleep(5)
        self._driver.find_element(By.CSS_SELECTOR, "#formsubmit").click()
        cookies = self._driver.get_cookies()
        db = shelve.open("../conf/cookies/cookies")
        db["cookies"] = cookies
        db.close()
    def login_session(self):
        self._driver.get(self._base_url)
        db = shelve.open("../conf/cookies/cookies")
        cookies = db["cookies"]
        for cookie in cookies:
            if "expiry" in cookie.keys():
                cookie.pop("expiry")
            self._driver.add_cookie(cookie)
        self._driver.refresh()
        self._driver.get(self._base_url)
        db.close()
        time.sleep(2)
    def checkSession(self):
        try:
            self.wait_for_click((By.CSS_SELECTOR, ".username-hide-on-mobile"), 10)
        except:
            return 0
        return 1